//
//  LSHomelessBeggerInfoSearchViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/27.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSHomelessBeggerInfoSearchViewController.h"
#import "LSInfoSearchTableViewCell.h"
#import "LSHomelessBeggerInfoDetailViewController.h"

#define headerSearchViewHeight 98
#define CountPerPage 10

@interface LSHomelessBeggerInfoSearchViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *cardTypeTF;
@property (nonatomic, strong) UITextField *cardNumberTF;
@property (nonatomic, assign) int tableViewPage;
@property (nonatomic, strong) NSMutableArray <NSDictionary *> *dataArrayM;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@end

static NSString *LSInfoSearchTableViewCellID = @"LSInfoSearchTableViewCellID";

@implementation LSHomelessBeggerInfoSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"流浪乞讨人员信息查询";
    [self setUpHeaderSearchView];
    [self.view addSubview:self.tableView];
    [self loadData];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)loadData {
    self.tableViewPage = 1;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"name":self.nameTF.text,@"idcard":self.cardNumberTF.text,@"pageSize":[NSString stringWithFormat:@"%d",CountPerPage],@"curPage":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:Vagrancylist param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [self.tableView.mj_header endRefreshing];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                self.dataArrayM = dataArray.mutableCopy;
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                [self.tableView reloadData];
            } else {
                [MBProgressHUD showTipMessageInWindow:responseObject[@"message"]];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.tableViewPage++;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"name":self.nameTF.text,@"idcard":self.cardNumberTF.text,@"pageSize":[NSString stringWithFormat:@"%d",CountPerPage],@"curPage":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:Vagrancylist param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                [self.dataArrayM addObjectsFromArray:dataArray];
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [self.tableView.mj_footer endRefreshing];
                }
                [self.tableView reloadData];
            } else {
                self.tableViewPage--;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.tableViewPage--;
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (void)setUpHeaderSearchView {
    UIView *headerSearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSearchViewHeight)];
    headerSearchView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerSearchView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight-0.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerSearchView addSubview:headerViewBottomLineView];
    
    // 姓名输入框
    UITextField *nameTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 5+4, (ScreenWidth-30), 36)];
    self.nameTF = nameTF;
    nameTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    nameTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    nameTF.layer.borderWidth = 1;
    nameTF.returnKeyType = UIReturnKeySearch;
    nameTF.placeholder = @"请输入姓名";
    nameTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    nameTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:nameTF];
    
//    UITextField *cardTypeTF = [[UITextField alloc] initWithFrame:CGRectMake(ScreenWidth-((ScreenWidth-30)*0.4)-15, 5+4, (ScreenWidth-30)*0.4, 36)];
//    self.cardTypeTF = cardTypeTF;
//    cardTypeTF.delegate = self;
//    cardTypeTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
//    cardTypeTF.layer.borderColor = hexColor(dbdbdb).CGColor;
//    cardTypeTF.layer.borderWidth = 1;
//    cardTypeTF.returnKeyType = UIReturnKeySearch;
//    cardTypeTF.placeholder = @"请选择证件类型";
//    cardTypeTF.text = @"居民身份证";
//    cardTypeTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
//    cardTypeTF.leftViewMode = UITextFieldViewModeAlways;
//    UIImageView *timeSelectFinisherTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//    timeSelectFinisherTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
//    cardTypeTF.rightView = timeSelectFinisherTFRightViewImageView;
//    cardTypeTF.rightViewMode = UITextFieldViewModeAlways;
//    [headerSearchView addSubview:cardTypeTF];
//    
//    UILabel *cardTypeTipLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-30)*0.3+15+5, 5+4, ScreenWidth-30-((ScreenWidth-30)*(0.3+0.4))-10, 36) andText:@"身份证件类型" andTextColor:hexColor(333333) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentRight];
//    [headerSearchView addSubview:cardTypeTipLabel];
    
    UITextField *cardNumberTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 54+4, ScreenWidth-30-55-15, 36)];
    self.cardNumberTF = cardNumberTF;
    cardNumberTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    cardNumberTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    cardNumberTF.layer.borderWidth = 1;
    cardNumberTF.returnKeyType = UIReturnKeySearch;
    cardNumberTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    cardNumberTF.placeholder = @"请填写身份证号";
    cardNumberTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    cardNumberTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:cardNumberTF];
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-15-55, 54+4, 55, 36)];
    searchButton.layer.cornerRadius = 4;
    searchButton.layer.masksToBounds = true;
    searchButton.backgroundColor = NAV_COLOR;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [headerSearchView addSubview:searchButton];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertC addActionTarget:alertC title:@"居民身份证" color:NAV_COLOR action:^(UIAlertAction *action) {
        textField.text = @"居民身份证";
    }];
    [alertC addCancelActionTarget:alertC color:NAV_COLOR title:@"取消"];
    [self presentViewController:alertC animated:true completion:nil];
    return false;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSInfoSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSInfoSearchTableViewCellID forIndexPath:indexPath];
    NSDictionary *dataDict = self.dataArrayM[indexPath.row];
    cell.mainTitleLabel.text = [ValidateUtils validateNull:dataDict[@"name"]];
//    NSString *timeStampString = @"";
//    if (![dataDict[@"updateDate"] isKindOfClass:NSNull.class] && [dataDict[@"updateDate"] integerValue] > 0) {
//        timeStampString = dataDict[@"updateDate"];
//    } else {
//        timeStampString = dataDict[@"createDate"];
//    }
//    NSTimeInterval interval = [timeStampString doubleValue] / 1000.0;
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSString *dateString = [formatter stringFromDate: date];
//    cell.bottomLabel.text = dateString;
    if (![[ValidateUtils validateNull:dataDict[@"idcard"]] isEqualToString:@""]) {
        cell.bottomLabel.text = [NSString stringWithFormat:@"身份证号：%@",[ValidateUtils validateNull:dataDict[@"idcard"]]];
    } else {
        cell.bottomLabel.text = @"";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSHomelessBeggerInfoDetailViewController *homelessBeggerInfoDetailVC = [[LSHomelessBeggerInfoDetailViewController alloc] init];
    homelessBeggerInfoDetailVC.dataFromWebDict = self.dataArrayM[indexPath.row];
    [self.navigationController pushViewController:homelessBeggerInfoDetailVC animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSInfoSearchTableViewCellHeight;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight)];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.backgroundColor = hexColor(EEEEEE);
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:LSInfoSearchTableViewCell.class forCellReuseIdentifier:LSInfoSearchTableViewCellID];
    }
    return _tableView;
}

- (NSMutableArray <NSDictionary *> *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
